package com.eliota.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.eliota.entity.User;
import com.eliota.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 *
 *
 * @author M.G
 * @create 2023-03-26 23:43
 * @date 2023/3/26 23:43
 *
 * Token生成工具类
 */

@Component
public class TokenUtil {

    private static UserService staticUserService;
    @Resource
    private UserService userService;
    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }

    public static String getToken(String userId, String sign) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>id:"+userId);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>password:" + sign);
        //？
        //enJ?32,enj?64,43
        //(eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9. {"typ":"JWT","alg":"HS256"}
        // eyJhdWQiOiIxIiwiZXhwIjoxNjc5ODk0NTU4fQ. {{"aud":"1","exp":1679894558}}
        // 8Tl-Z1EuzRmJs6JgrdjEj2mrJIeEYPZNlH8qVj7p-g4)
        //withAudience,加密观众
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 第二参数sign作为 作为 token 的密钥
    }



    /*
     * 获取当前登陆的用户信息
     * */
    public static User getCurrentUser() {
        try {
            //获取servlet的request
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            System.out.println("TokenUtil:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>request"+request.toString());
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }

        return null;
    }
}
